/**
 *
 * @author ace
 * @create 2017/7/22
 */
class NumberKeyboard extends ComponentEx {

    private close: eui.Rect;

    private group: eui.Group;
    private btn_0: eui.Button;
    private btn_1: eui.Button;
    private btn_2: eui.Button;
    private btn_3: eui.Button;
    private btn_4: eui.Button;
    private btn_5: eui.Button;
    private btn_6: eui.Button;
    private btn_7: eui.Button;
    private btn_8: eui.Button;
    private btn_9: eui.Button;
    private btn_cancel: eui.Button;
    private btn_confirm: eui.Button;

    private lab_num: any;
    private maxChars: number = -1;
    private numArr: number[] = [];

    constructor() {
        super();
        this.skinName = "NumberKeyboardSkin";
    }

    childrenCreated() {
        super.childrenCreated();

        this.width = acelab.width;
        this.height = acelab.height;

        let arr: eui.Button[] = [
            this.btn_0, this.btn_1, this.btn_2, this.btn_3, this.btn_4,
            this.btn_5, this.btn_6, this.btn_7, this.btn_8, this.btn_9
        ];

        for (let i: number = 0; i < arr.length; i++) {
            arr[i].name = "" + i;
            arr[i].addEventListener(egret.TouchEvent.TOUCH_TAP, this.clickHandler, this);
        }

        this.btn_cancel.addEventListener(egret.TouchEvent.TOUCH_TAP, this.clickHandler, this);
        this.btn_confirm.addEventListener(egret.TouchEvent.TOUCH_TAP, this.clickHandler, this);

        this.close.addEventListener(egret.TouchEvent.TOUCH_TAP, this.clickHandler, this);
    }

    private clickHandler(e: egret.TouchEvent) {
        switch (e.currentTarget) {
            case this.btn_cancel:
                if (this.lab_num) {
                    this.numArr.pop();
                    this.lab_num.text = this.numArr.join("");
                }
                break;
            case this.btn_confirm:
            case this.close:
                this.hide();
                break;
            default:
                if (this.lab_num && this.numArr.length < this.maxChars) {
                    this.numArr.push(e.currentTarget.name);
                    this.lab_num.text = this.numArr.join("");
                }
                break;
        }
    }

    open(label: eui.TextInput, maxChars: number = 100) {
        this.show();

        this.numArr = [];
        this.lab_num = label;
        this.lab_num.text = '';
        this.maxChars = maxChars;

        this.group.x = this.lab_num.localToGlobal(0, 0).x + (this.lab_num.width - this.group.width) / 2;
        this.group.y = this.lab_num.localToGlobal(0, 0).y + this.lab_num.height;
    }

    show() {
        super.show();

        GameSound.play('sound_panel_show');

        if (!acelab.contains(this)) {
            acelab.addChild(this);
        }
    }

    hide() {
        super.hide();

        GameSound.play('sound_panel_close');

        this.lab_num = null;

        if (acelab.contains(this)) {
            acelab.removeChild(this);
        }
    }
}